

/* 绑定 chinaCity.json中的城市信息 */
var SetupCity = (function () {
    var cityData;
    var provinceModel;
    var cityModel;
    var regionModel;
    // path 所需调用json的当前路径， fun 执行函数
    function getCityData(fun) {
        $.ajax({
            url: "/web-tribalc/json/chinaCity.json",
            cache: false,
            success: function (result) {
                fun(result);
            }
        });
    }
    // path 所需调用json的当前路径.   province 省input元素.    city 市input元素.  region 地区input元素.
    function setAddressSelect(province, city, region) {
        getCityData(function (result) {
            cityData = result;
            provinceModel = province;
            cityModel = city;
            regionModel = region;
            console.log(result);

            setupOptionSelect(province, result.province);
            setupOptionSelect(city, result.province[0]["city"]);
            setupOptionSelect(region, result.province[0]["city"][0]["county"]);
            bindProvinceChange();
        });
    }

    function bindProvinceChange() {
        $(provinceModel).change(function () {
            cityData.province.forEach(function (data) {
                if (data["name"] == $(provinceModel).val()) {
                    setupOptionSelect(cityModel, data["city"]);
                    setupOptionSelect(regionModel, data["city"][0]["county"]);
                    bindCityChange(cityModel, data["city"]);
                }
            });
        });
    }

    function bindCityChange(model, data) {
        $(model).change(function () {
            console.log("city change" + $(model).val());
            console.log($(model));

            data.forEach(function (data) {
                if (data["name"] == $(model).val()) {
                    setupOptionSelect(regionModel, data["county"]);
                }
            });
        })
    }

    function setupOptionSelect(model, data) {
        var elements = $(model).children();
        elements.remove();
        for (var i = 0; i < data.length; i++) {
            $(model).prepend("<option>" + data[i]["name"] + "</option>");
        }
    }
    return {
        getCity: function(path, fun) {
            getCityData(path ,fun);
        },
        setAddress: setAddressSelect
    }

})();